/**
 * @description 产品控制器
 * @author 韩
 */

const { randomUUID } = require("crypto")
const product_category_link_controller = require("../../link/product_category_controller")
const product_brand_link_controller = require("../../link/product_brand_controller")
const product_profession_link_controller = require("../../link/product_profession_controller")
const product_skus_link_controller = require("../../link/product_skus_controller")
const product_spec_link_controller = require("../../link/product_spec_controller")
const product_seo_link_controller = require("../../link/product_seo_controller")
const skuUpdate = require("../../../controller/product/list/SKU.CONTROLLER").controller_save
const skuFind = require("../../../controller/product/list/SKU.CONTROLLER").controller_find
const model = require("../../../model/product/list/PRODUCT.MODEL")
const { getFilter } = require("../../../utils/setFilter")
const dayjs = require("dayjs")
// 创建一个内容
const controller_save = async ({
    id = undefined,
    cateId = undefined,
    brandId = undefined,
    professionId = undefined,
    intro = undefined,
    title = undefined,
    masterImages = undefined,
    sku = undefined,
    specContent = undefined,
    price = undefined,
    shelfTime = undefined,
    sellPrice = undefined,
    rackDateTime = undefined,
    description = undefined,
    sort = undefined,
    status = undefined,
    seoTitle = undefined,
    seoDescription = undefined,
    seoKeyWords = undefined,
    seoUrl = undefined,
    takeDown = undefined,
    snapshot = undefined,

    /**
     * skus示例：
     * { id:1,productId:pd1,skus:"颜色：红色,尺码：S",price:12,stock:1230}
     */
}) => {
    try {
        const params = {
            id: randomUUID(), shelfTime, title, intro, masterImages: JSON.stringify(masterImages), price, sellPrice, rackDateTime, description, sort, status
        }
        let result = null;
        if (!id) {
            // 添加创建
            result = await model.create({
                createDate: dayjs(),
                ...params
            })
        } else {
            // 更新修改
            result = await model.findOneAndUpdate({ id: id }, {
                $set: {
                    ...params
                }
            }, { new: true })
        }

        if (result) {
            const {
                id, title, intro, masterImages, price, sellPrice, rackDateTime, description, sort, status, shelfTime
            } = result


            //更新产品-分类关联表
            await product_category_link_controller.controller_save({
                productId: result.id,
                categoryId: cateId,
            })

            //更新产品-品牌关联表
            await product_brand_link_controller.controller_save({
                productId: result.id,
                brandId: brandId,
            })

            //更新行业-产品关联表
            await product_profession_link_controller.controller_save({
                productionId: result.id,
                professionId: professionId,
            })

            //更新 产品-sku表
            await product_skus_link_controller.controller_save({
                productId: id,
                skus: sku.map(item => ({
                    productId: id,
                    skuAll: JSON.stringify(item),
                    sku: item.sku,
                    productId: id,
                    price: item.piece,
                    linePiece: item.linePiece,
                    imgUrl: item.imgUrl,
                    stock: item.stock,
                })),
            })
            //更新SEO信息
            const seoUpdateRes = await product_seo_link_controller.controller_save({
                productId: result.id,
                seoTitle,
                seoDescription,
                seoKeyWords,
                seoUrl,
                takeDown,
                snapshot,
            })
            console.log("SEO信息保存成功", seoUpdateRes)

            //更新规格表
            await product_spec_link_controller.controller_save({
                productId: id,
                specContent: JSON.stringify(specContent),
            })


            return {
                code: 0,
                msg: "成功",
                data: {
                    id, cateId, intro, title, masterImages, price, sellPrice, rackDateTime, description, sort, status,
                    seoTitle,
                    seoDescription,
                    seoKeyWords,
                    seoUrl,
                    takeDown,
                    snapshot,
                }
            }
        }
        console.log("报错", result)
        return {
            code: 100,
            msg: "失败",
        }
    } catch (error) {
        console.log("产品控制器报错:", error)
        return {
            code: 100,
            msg: "失败",
        }
    }
}

// 查询列表 
const controller_find = async ({ current, pageSize, id = undefined, title = undefined, status = undefined }) => {
    try {

        let params = {
            id, title, status
        }
        filter = getFilter(params)

        /**
         * @description 聚合查询
         * 
         */

        const pipeline = [
            {
                $match: {
                    ...filter,
                    deleteFlag: false
                }
            },
            { $sort: { sort: 1 } },
            { $skip: (current - 1) * pageSize },
            { $limit: pageSize },
            //关联查询商品品牌
            // {
            //     $lookup: {
            //         from: "product_brand_links",
            //         localField: "brandId",
            //         foreignField: "productionId",
            //         as: "brands"
            //     },
            // },
            //关联查询行业
            // {
            //     $lookup: {
            //         from: "product_profession_links",
            //         localField: "productId",
            //         foreignField: "productionId",
            //         as: "professions"
            //     }
            // },

            {
                //关联查询商品分类
                $lookup: {
                    from: "product_category_links",
                    let: { productId: "$id" },
                    pipeline: [
                        {
                            $match: {
                                $expr: { $eq: ["$productId", "$$productId"] }
                            }
                        },
                        { $project: { categoryId: 1 } }
                    ],
                    as: "categoryData"
                },
                //关联查询商品品牌
                $lookup: {
                    from: "product_brand_links",
                    let: { productId: "$id" },
                    pipeline: [
                        {
                            $match: {
                                $expr: { $eq: ["$productId", "$$productId"] }
                            }
                        },
                        { $project: { brandId: 1 } }
                    ],
                    as: "brandData"
                }
            },
            {
                $unwind: {
                    path: "$categoryData",
                    preserveNullAndEmptyArrays: true
                }
            },
            {
                //添加字段
                $addFields: {
                    categoryId: { $ifNull: ["$categoryData.categoryId", null] },
                    brandId: { $ifNull: ["$brandData.brandId", null] },
                }
            },
            {
                //删除字段
                $project: {
                    categoryData: 0,
                    brandData: 0
                }
            }
            //关联查询sku
            // {
            //     $lookup: {
            //         from: "product_skus_links",
            //         localField: "id",
            //         foreignField: "productId",
            //         as: "skus"
            //     },
            // },
            // 转换数据结构
            // {
            //     $project: {
            //         _id: 1,
            //         name: 1,
            //         price: 1,
            //         // 其他商品字段...
            //         categoryIds: {
            //             $map: {
            //                 input: "$categories",
            //                 as: "cat",
            //                 in: "$$cat.categoryId"
            //             }
            //         },
            //         brandIds: {
            //             $map: {
            //                 input: "$brands",
            //                 as: "brand",
            //                 in: "$$brand.brandId"
            //             }
            //         },
            //         industryIds: {
            //             $map: {
            //                 input: "$industries",
            //                 as: "industry",
            //                 in: "$$industry.industryId"
            //             }
            //         }
            //     }
            // }
        ]


        const list = await model.aggregate(pipeline)
        const totalCount = await model.countDocuments(filter)
        return {
            code: 0,
            msg: "查询成功",
            data: {
                list,
                totalCount
            }
        }
    } catch (error) {
        return {
            code: 100,
            msg: "查询失败",
            data: {
                list: [],
                totalCount: 0
            }
        }
    }
}


/**@description 根据id查详情 */
const controller_get = async ({ id, title }) => {
    try {
        const res = await model.findOne({
            id
        })
        if (res) {
            // console.log("产品详情查询：", res);
            const { id, title, masterImages, price, sellPrice, description, satus, shelfTime, intro } = res;

            //查询分类信息
            const resCategory = await product_category_link_controller.controller_get({
                productId: id
            })
            //查询品牌信息
            const resBrand = await product_brand_link_controller.controller_get({
                productId: id
            })

            //查询行业信息
            const resProfession = await product_profession_link_controller.controller_get({
                productId: id
            })

            //查询seo配置
            const resSeo = await product_seo_link_controller.controller_get({
                productId: id
            })
            console.log("SEO配置信息：", id, resSeo.data)


            //查询规格配置
            const resSpec = await product_spec_link_controller.controller_get({ productId: id })
            //查询SKU信息
            const { list } = await product_skus_link_controller.controller_find({ productionId: id })
            const sku = list.map(item => {
                const skuAll = JSON.parse(item.skuAll);
                return {
                    ...skuAll,
                    stock: item.stock,
                    piece: item.piece,
                    linePiece: item.linePiece,
                    imgUrl: item.imgUrl,

                }
            })
            return {
                code: 0,
                msg: "查询成功",
                data: {
                    id, title, masterImages, price, sellPrice, description, satus,
                    sku,
                    shelfTime,
                    intro,
                    cateId: resCategory?.data?.categoryId,
                    brandId: resBrand.data?.brandId,
                    professionId: resProfession.data?.professionId,
                    specContent: resSpec.data?.specContent,
                    ...resSeo.data
                }
            }
        } else {
            return {
                code: 100,
                msg: "未找到对应菜单数据"
            }
        }
    } catch (error) {
        console.log("查详情报错：", error)
        return {
            code: 100,
            msg: "查详情报错"
        }
    }
}

// 删除
const controller_delete = async ({ ids = [], id = undefined }) => {
    try {
        //物理删除
        // const res = await model.deleteMany({
        //     id: { $in: ids }
        // });
        // 逻辑删除
        const res = await model.findOneAndUpdate({ id: id }, {
            $set: {
                deleteFlag: true
            }
        }, { new: true })

        if (res) {
            return {
                code: 0,
                msg: `删除成功`
            }
        } else {
            return {
                code: 100,
                msg: `删除失败`
            }
        }
    } catch (error) {
        console.log("删除控制器出错", error)
    }

}
module.exports = {
    controller_save,
    controller_find,
    controller_get,
    controller_delete,
}